/*
 * File: util.service.ts
 * File Created: Tuesday, 5th June 2018 3:23:48 pm
 * Author: songyz
 * Description:
 * -----
 * Last Modified: Thursday, 14th June 2018 11:16:04 am
 * Modified By: Wizard
 * -----
 *  All rights reserved.
 */

var CryptoJS:any = require("crypto-js");
const KJUR:any = require('jsrsasign').KJUR;
const KEYUTIL:any = require('jsrsasign').KEYUTIL;
const hextob64:any =  require('jsrsasign').hextob64;

var key = _Crypto().enc.Utf8.parse("ABCDEFGHIJXingye");
var AESkey = _Crypto().enc.Utf8.parse("APeRZtUgfZXiKhHe");
var iv = _Crypto().enc.Utf8.parse('9876543210XingYe');
function Encrypt(word:any) {var srcs = _Crypto().enc.Utf8.parse(word);
var encrypted = _Crypto().AES.encrypt(srcs, key, {iv: iv, mode: _Crypto().mode.CBC, padding: _Crypto().pad.Pkcs7});return encrypted.toString();}
function Decrypt(word:any) {var decrypt = _Crypto().AES.decrypt(word, key, {iv: iv, mode: _Crypto().mode.CBC, padding: _Crypto().pad.Pkcs7});return _Crypto().enc.Utf8.stringify(decrypt).toString();}
function aesEncrypt(data:any,keyVal:any) {var srcs = _Crypto().enc.Utf8.parse(data); var encrypted = _Crypto().AES.encrypt(srcs, keyVal, {iv: iv, mode: _Crypto().mode.CBC, padding: _Crypto().pad.Pkcs7}); return encrypted.toString();}
function aesDecrypt(data:any,keyVal:any) {var final_data = data.replace(/[\n]/g,"").replace(/[\r\n]/g,"");var decrypt = _Crypto().AES.decrypt(final_data, keyVal, {iv: iv, mode: _Crypto().mode.CBC, padding: _Crypto().pad.Pkcs7});return _Crypto().enc.Utf8.stringify(decrypt).toString();}
function randomWord(randomFlag:any,min:any,max?:any){let str="",range=min,arr=['a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N', 'O','P','Q','R','S','T','U','V','W','X','Y','Z'];if(randomFlag){range=Math.round(Math.random()*(max-min))+min;}for(let i=0;i<range;i++){var pos=Math.round(Math.random()*(arr.length-1));str +=arr[pos];}return str;}
var aesKey = randomWord(false,16,16);
function publicAesEncrypt(data:any){var schar1= '...';var aeskey_m = _Crypto().enc.Utf8.parse(aesKey);var EncryptResult = _Crypto().MD5(aesKey+JSON.stringify(data))+ schar1+aesEncrypt(JSON.stringify(data),aeskey_m) + schar1 + aesEncrypt(aesKey,AESkey);console.log("加密结果："+EncryptResult);return EncryptResult;}
function publicAesDecrypt(data:any){var aeskey_m = _Crypto().enc.Utf8.parse(aesKey);
var Dncryptdata=aesDecrypt(data, aeskey_m);return JSON.parse(Dncryptdata);}



function _Crypto ():any{
	return CryptoJS
}
function parseSetData(value:any) {
    function parseDate(obj:any) {
        for (const k in obj) {
            if (obj[k] instanceof Date) {
                obj[k] = 'date@@' + obj[k].valueOf();
            } else if (typeof obj[k] === 'object') {
                parseDate(obj[k]);
            }
        }
    }
    let type = '';
    type = typeof value;
    if ( value instanceof Date ) {
        type = 'date';
        value = value.valueOf();
    }
    switch (type) {
        case 'object':
            parseDate(value);
            value = type + '@@' + JSON.stringify(value);
            break;
        case 'function':
            throw new Error('localStorage无法存储函数类型');
        default:
            value = type + '@@' + value;
    }
    return value;
}

function parseGetData(result:any) {
    function parseDate(obj:any) {
        for (const k in obj) {
            if (typeof obj[k] === 'string' && obj[k].indexOf('date@@') !== -1) {
                const content = obj[k].split('date@@')[1];
                obj[k] = new Date(JSON.parse(content));
            } else if (typeof obj[k] === 'object') {
                parseDate(obj[k]);
            }
        }
    }
    try {
        const type = result.split('@@')[0];
        const content = result.split(type + '@@')[1];
        if (type === 'string') {
            return content;
        } else if (type === 'date') {
            return new Date(JSON.parse(content));
        } else {
            const retObject = JSON.parse(content);
            parseDate(retObject);
            return retObject;
        }
    } catch (error) {

    }
    return null;
}

export class UtilsService {
    localStorage = {
        get(name: string): any {
            let result = localStorage.getItem(name);
            result = parseGetData(result);
            // alert(result);
            return result;
        },
        set(name: string, value: any) {
            value = parseSetData(value)
            localStorage.setItem(name, value);
        },
        remove(name: string) {
            localStorage.removeItem(name);
        }
    };
    cookie = {
        set (name: string, value:any, expiredays: number = 30) {
            value = parseSetData(value)
            const exp = new Date();
            exp.setTime(exp.getTime() + expiredays * 24 * 60 * 60 * 1000);
            document.cookie = name + '=' + value + ';expires=' + exp.toUTCString();
        },
        get(name: string): any {
            let arr;
            const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
            if (arr = document.cookie.match(reg)) {
                let result = arr[2];
                // result = result.substring(1,result.length-1);
                result = parseGetData(result);
                return result;
            } else {
                return null;
            }
        },
        remove(name: string) {
            function getCookie(n:any) {
                let arr;
                const reg = new RegExp('(^| )' + n + '=([^;]*)(;|$)');
                if (arr = document.cookie.match(reg)) {
                    return arr[2];
                } else {
                    return null;
                }
            }
            const exp = new Date();
            exp.setTime(exp.getTime() - 1);
            const cval = getCookie(name);
            if (cval != null) {
            document.cookie = name + '=' + cval + ';expires=' + exp.toUTCString();
            }
        }
    };

    crypto = {
        EncryptKey(timestamp?:any) { // RSA 加密
            const pk = "-----BEGIN PUBLIC KEY-----"+this.publicKey+"-----END PUBLIC KEY-----"
            var pub = KEYUTIL.getKey(pk);
            var enc = KJUR.crypto.Cipher.encrypt(this.key+'|'+timestamp,pub);
            return window.btoa(enc)
            // return hextob64(enc)
            // return enc.toUpperCase();
        },
        decrptKey(data?:any){ // RSA 解密
            const pk = "-----BEGIN PRIVATE KEY-----"+this.privateKey+"-----END PRIVATE KEY-----"
            var prv = KEYUTIL.getKey(pk)
            var dec = KJUR.crypto.Cipher.decrypt(window.atob(data),prv)
            return dec
            // return ba64tohex(dec)
        },
        publicKey :process.env.VUE_APP_publicKey,
        privateKey:process.env.VUE_APP_privateKey,
		staticKey : "APeRZtUgfZXiKhHe",
		key:"",
		accesscode:"",
		isConnected:true,
		UUID(){
			const arr = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
			let key = '';
			arr.forEach(() => {
				
				const index= Math.ceil(Math.random()*15)
				key += arr[index]
			})
			return key;
		},
		URLencodeForBase64(a: any) {
		    return escape(a).replace(/\+/g, "%2B").replace(/\"/g, "%22").replace(/\'/g, "%27").replace(/\//g, "%2F");
		},
		publicAesEncrypt(d:any){
			return publicAesEncrypt(d)
		},
		publicAesDecrypt(d:any){
			return publicAesDecrypt(d)
		},
		encrypt(word:any,keys?:any,pad?:any) {
			const key:any = _Crypto().enc.Utf8.parse(keys||this.key);  //密钥
			const iv = _Crypto().enc.Utf8.parse(pad||'9876543210XingYe');   //密钥偏移量
			let srcs = _Crypto().enc.Utf8.parse(word);
			let encrypted = _Crypto().AES.encrypt(srcs, key, { iv: iv, mode: _Crypto().mode.CBC, padding: _Crypto().pad.Pkcs7 });
			// let encrypted = _Crypto().AES.encrypt(srcs, key, { iv: iv, mode: _Crypto().mode.CBC});
            const base64str = _Crypto().enc.Base64.stringify(encrypted.ciphertext);
            return base64str;
			// return this.URLencodeForBase64(base64str);
		},
		decrypt(content:any,keys?:any,pad?:any): string{
			const key:any = _Crypto().enc.Utf8.parse(keys||this.key);  //密钥
			// console.log(key)
			const iv = _Crypto().enc.Utf8.parse(pad||'9876543210XingYe');   //密钥偏移量
			const result = _Crypto().AES.decrypt(content.replace(/\s/g,""), key, { iv: iv, mode: _Crypto().mode.CBC, padding: _Crypto().pad.Pkcs7 });
			return _Crypto().enc.Utf8.stringify(result);
		},
		MD5encrypt(word:any,timestamp?:any,keys?:any) {
            // if(!this.key){
                this.key = this.UUID();
            // }
            const key:any = keys||this.key
            let md = `${word}|${timestamp}|${key}`
            // console.log(md,'md')
			return _Crypto().MD5(md).toString()
		}
    };
	chooseLocation(){
		return new Promise(function(resolve,reject){
			uni.getSetting({
				success(res) {
					if (!res.authSetting['scope.record']) {
						uni.authorize({
							scope:"scope.userLocation",
							success(res) {
								uni.chooseLocation({
									success(res) {
										resolve(res)
									}
								})
							}
						})
					} else {
						uni.chooseLocation({
							success(res) {
								resolve(res)
							}
						})
					}
				}
			})
		})
	}
}

